const express = require("express");
const teamRouter = express.Router();
const DB = require("./../db/config");
const upload = require("./../db/uploadconfig");
module.exports = teamRouter;

/**
 * 添加医生团队
 *@param {String} tname 团队名称r equired
 *@param {String} tdes 团队描述 required
 *@param {String[Array]} doctorslist 加入团队的医生数组 JOSN.stingify()字符串
 *@param {File} tphoto 团队头像 required
 */
teamRouter.route("/team/add").post(upload.single("tphoto"), (req, res) => {
  let { tname, tdes, doctorslist } = req.body;
  let tphoto = req.file.filename;
  doctorslist = JSON.parse(doctorslist);
  new Promise((resolve, reject) => {
    let sql = "insert into teams (tname,tdes, tphoto) values(?,?,?);";
    let param = [tname, tdes, tphoto];
    let cb = (err, data) => {
      console.log(data);
      if (!err) {
        resolve({ code: 0, msg: "添加团队数据成功1", data });
      } else {
        reject({ code: 4002, msg: "添加团队数据失败1" });
      }
    };
    DB.connect(sql, param, cb);
  })
    .then((data) => {
      return new Promise((resolve, reject) => {
        let tid = data.data.insertId;
        let sql = "insert into teamdoctortable (tid,did,manager) values ";
        let param = [];
        let strArr = [];
        if (doctorslist && doctorslist.length === 0) {
          resolve({ code: 0, msg: "添加团队数据成功", data: [] });
        } else {
          doctorslist.forEach((el) => {
            strArr.push("(?,?,?)");
            param.push(tid, el.did, el.manager);
          });
          sql = sql + strArr.join(",");
          // console.log(sql);
          // console.log(param);
          let cb = (err, data) => {
            if (!err) {
              resolve({ code: 0, msg: "添加团队数据成功", data: [] });
            } else {
              reject({ code: 4002, msg: "添加团队数据失败", data: [] });
            }
          };
          DB.connect(sql, param, cb);
        }
      });
    })
    .then((data) => {
      res.json(data);
    })
    .catch((data) => {
      res.json(data);
    });
});

/**
 * 分页查询所有团队数据和团队医生信息
 * 多条件搜索功能
 * @param {Number} limit 每页几条数据,
 * @param {Number} page 第几页
 * @param {String} searchTeamName 搜索的团队名字
 * @param {String} searchManagerDoctor 搜索的团队医生名字
 */

teamRouter.route("/team/list").get((req, res) => {
  //要先查询指定页的团队后，再根据团队查关联的医生。
  let { limit, page, searchTeamName, searchManagerDoctor } = req.query;
  limit = Number(limit);
  page = Number(page);
  let startIndex = (page - 1) * limit;

  new Promise((resolve, reject) => {
    let sql = `SELECT tid FROM teams  where tdeletestate = '0'`;
    let param = [];
    if (searchTeamName !== "") {
      sql += ` and  tname LIKE ?`;
      param.push("%" + searchTeamName + "%");
    }
    sql += ` limit ?,?;select count(*) as count from teams where tdeletestate = '0';`;
    param.push(startIndex, limit);
    let cb = (err, data) => {
      console.log(err);
      console.log("count:", data);
      if (!err) {
        resolve({
          code: 0,
          msg: "查询成功",
          data: data[0],
          count: data[1][0].count,
        });
      } else {
        reject({ code: 4002, msg: "查询失败", data: [] });
      }
    };
    DB.connect(sql, param, cb);
  })
    .then((resData) => {
      console.log(resData);
      let tidArr = [];
      resData.data.forEach((el) => {
        tidArr.push(el.tid);
      });
      // console.log(tidArr);
      return new Promise((resolve, reject) => {
        let sql = `SELECT t.tid as tid, tname, tdes, tphoto,tdt.did,manager,dname,dsex,dsid,dtel,dfeaturs,jid,dphoto 
        FROM teams AS t LEFT JOIN teamdoctortable AS tdt ON t.tid = tdt.tid left join
      doctorstable AS d ON tdt.did = d.did WHERE 1=1`; // ");"
        let param = [];
        let tempStr = [];
        if (tidArr.length !== 0) {
          sql += " and t.tid IN (";
          tidArr.forEach((el) => {
            tempStr.push("?");
            param.push(el);
          });
          sql += tempStr.join(",");
          sql += ")";
        }

        if (searchManagerDoctor !== "") {
          sql += ` AND dname  LIKE ? AND manager = '1'`;
          param.push("%" + searchManagerDoctor + "%");
        }
        console.log(sql);
        console.log(param);

        let cb = (err, data) => {
          console.log(err);
          console.log(data);
          if (!err) {
            resolve({
              code: 0,
              msg: "查询所有团队数据和团队医生信息成功",
              data: data.length !== 0 ? data : resData.data,
              count: resData.count,
            });
          } else {
            reject({
              code: 4002,
              msg: "查询所有团队数据和团队医生信息失败",
              data: [],
            });
          }
        };
        DB.connect(sql, param, cb);
      });
    })
    .then((resData) => {
      res.json(resData);
    })
    .catch((resData) => {
      res.json(resData);
    });
});

/**
 * 删除团队
 * @param {Number} tid 团队ID required
 */
teamRouter.route("/team/delete").post((req, res) => {
  new Promise((resolve, reject) => {
    let tid = req.body.tid;
    let sql = `update teams set tdeletestate = '1' where tid =?;`;
    let param = [tid];
    let cb = (err, data) => {
      if (!err) {
        resolve({ code: 0, msg: "删除团队成功", data: [] });
      } else {
        reject({ code: 4002, msg: "删除团队失败", data: [] });
      }
    };
    DB.connect(sql, param, cb);
  })
    .then((resData) => {
      return new Promise((resolve, reject) => {
        let sql = "delete from teamdoctortable where tid =?;";
        let param = [tid];
        let cb = (err, data) => {
          if (!err) {
            resolve({ code: 0, msg: "删除团队和团队医生关系成功", data: [] });
          } else {
            reject({ code: 4002, msg: "删除团队和团队医生关系失败", data: [] });
          }
        };
        DB.connect(sql, param, cb);
      });
    })
    .then((data) => {
      res.json(data);
    })
    .catch((data) => {
      res.json(data);
    });
});
/**
 * 更新医生团队信息和团队的医生
 *@param {String} tname 团队名称r equired
 *@param {String} tdes 团队描述 required
 *@param {String[Array]} doctorslist 加入团队的医生数组 JOSN.stingify()字符串
 *@param {File} tphoto 团队头像
 */
teamRouter.route("/team/update").post(upload.single("tphoto"), (req, res) => {
  let { tid, tname, tdes, doctorslist } = req.body;
  let tphoto = "";
  doctorslist = JSON.parse(doctorslist);
  new Promise((resolve, reject) => {
    let sql = "update teams set tname=?,tdes=?"; //where tid=?;";
    let param = [tname, tdes];
    if (req.file) {
      tphoto = req.file.filename;
      sql = sql + `, tphoto = ?`;
      param.push(tphoto);
    }
    sql += " where tid=?;";
    param.push(tid);

    let cb = (err, data) => {
      // console.log("err",err);
      console.log("更新团队数据成功", data);
      if (!err) {
        resolve({ code: 0, msg: "更新团队数据成功1", data });
      } else {
        reject({ code: 4002, msg: "更新团队数据失败1" });
      }
    };
    DB.connect(sql, param, cb);
  })
    .then((resData) => {
      // console.log(resData);
      return new Promise((resolve, reject) => {
        let sql = "delete from teamdoctortable where tid = ?;";
        let param = [tid];
        let cb = (err, data) => {
          if (!err) {
            resolve({ code: 0, msg: "删除团队中已经添加的医生成功", data: [] });
          } else {
            reject({
              code: 4002,
              msg: "删除团队中已经添加的医生失败，更新未完成",
              data: [],
            });
          }
        };
        DB.connect(sql, param, cb);
      });
    })
    .then((resData) => {
      console.log(resData);
      return new Promise((resolve, reject) => {
        if (!doctorslist || doctorslist.length === 0) {
          resolve({ code: 0, msg: "更新团队数据成功2", data: [] });
        } else {
          let sql = "insert into teamdoctortable (tid,did,manager) values ";
          let param = [];
          let strArr = [];
          console.log("doctorslist:::::::::::::::>", doctorslist);
          doctorslist.forEach((el) => {
            strArr.push("(?,?,?)");
            param.push(tid, el.did, el.manager);
          });
          sql = sql + strArr.join(",");
          // console.log(sql);
          // console.log(param);
          let cb = (err, data) => {
            console.log(err);
            console.log(data);
            if (!err) {
              resolve({ code: 0, msg: "更新团队数据成功2", data: [] });
            } else {
              reject({ code: 4002, msg: "更新团队数据失败", data: [] });
            }
          };
          DB.connect(sql, param, cb);
        }
      });
    })
    .then((data) => {
      res.json(data);
    })
    .catch((data) => {
      res.json(data);
    });
});

/**
 * 获取一个团队信息或团队的医生
 * @param {Number} tid 团队ID required
 */
teamRouter.route("/team/findDetail").get((req, res) => {
  let tid = req.query.tid;
  let sql = `SELECT  t.tid as tid, tname, tdes, tphoto,tdt.did,manager,dname,dsex,dsid,dtel,dfeaturs,jname,dphoto FROM teams AS t LEFT JOIN teamdoctortable AS tdt ON t.tid = tdt.tid left JOIN
  doctorstable AS d ON tdt.did = d.did left join jobs as j on j.jid = d.jid where t.tid=?;`;
  let param = [tid];
  console.log(sql);
  console.log(param);
  let cb = (err, data) => {
    if (!err) {
      res.json({ code: 0, msg: "查询成功", data });
    } else {
      res.json({ code: 4002, msg: "查询失败", data });
    }
  };
  DB.connect(sql, param, cb);
});

/**
 * 获取所有团队列表数据
 */
teamRouter.route("/team/all").get((req, res) => {
  let sql = "SELECT * FROM teams  where tdeletestate = '0';";
  let param = [];
  let cb = (err, data) => {
    if (!err) {
      res.json({ code: 0, msg: "获取所有团队列表数据成功", data });
    } else {
      res.json({ code: 4002, msg: "获取所有团队列表数据失败", data: [] });
    }
  };
  DB.connect(sql, param, cb);
});

